<?php

/**
 * Created by PhpStorm.
 * User: freewheel
 * Date: 2016/10/13
 * Time: 9:52
 */

include_once("DB_Operation.php");
$textPattern = "/^[\\w&\\- ]+$/";

class Category_Operation extends DB_Operation
{
    public function operate($conn)
    {

    }

    public function getImageDir()
    {
        return "../images/categories/";
    }

    public function getResizedImageDir()
    {
        return "../images/re_categories/";
    }
}

class Insert_Category extends Category_Operation
{
    public function operate($conn)
    {
        global $textPattern;

        if (!isset($_POST['name'])) {
            throw new InvalidArgumentException("Missing parameter name!");
        }

        if (!preg_match($textPattern,$_POST['name'])){
            throw new InvalidArgumentException("name parameter is invalid!");
        }

        $imageExtension = $this->getImageExtension($this->getImageDir());
        $imageValidateMsg = $this->validate_image($imageExtension);
        if ($imageValidateMsg == "OK") {
            $stmt = $conn->prepare("INSERT INTO categories (catid , cname, extension) VALUES (NULL,:name,:extension)");
            $stmt->bindParam(':name', ($_POST['name']));
            $stmt->bindParam(':extension', $imageExtension);
            $stmt->execute();
//            echo "Add new Category successfully!<br/>";

            $this->upload_image($this->getImageDir(),$this->getResizedImageDir(), "category" . $conn->lastInsertId() . "." . $imageExtension);
        } else {
            throw new InvalidArgumentException($imageValidateMsg);
        }
    }
}

class Update_Category extends Category_Operation
{
    public function operate($conn)
    {
        global $textPattern;

        if (empty($_POST['catid'])) {
            throw new InvalidArgumentException("catid is missing");
        }

        $update_fields = '';
        $params = [];

        $params[':catid'] = $_POST['catid'];

        if (!empty($_POST['name'])) {
            if (!preg_match($textPattern,$_POST['name'])){
                throw new InvalidArgumentException("name parameter is invalid!");
            }

            $update_fields = $update_fields . "cname = :name";
            $params[':name'] = ($_POST['name']);
        }


        if (!empty($update_fields)) {
            $sql = "UPDATE categories SET  $update_fields  WHERE catid= :catid";
            $stmt = $conn->prepare($sql);
            $stmt->execute($params);

        }


        if (isset($_FILES["image"]) && trim(basename($_FILES["image"]["name"])) != "") {
            $imageExtension = $this->getImageExtension($this->getImageDir());
            $imageValidateMsg = $this->validate_image($imageExtension);
            if ($imageValidateMsg == "OK") {
                $stmt = $conn->prepare("UPDATE categories SET  extension = :extension  WHERE catid= :catid");
                $stmt->bindParam(':catid', $params[':catid']);
                $stmt->bindParam(':extension', $imageExtension);
                $stmt->execute();

                $this->upload_image($this->getImageDir(),$this->getResizedImageDir(), "category" . $params[':catid'] . "." . $imageExtension);
            } else {
                throw new InvalidArgumentException($imageValidateMsg);
            }
        }

//        echo "Update Category successfully!<br/>";
    }
}

class Delete_Category extends Category_Operation
{
    public function operate($conn)
    {
        try{
            $stmt = $conn->prepare("SELECT extension FROM categories  WHERE catid= :catid");
            $stmt->bindParam(':catid', $_POST['catid']);
            $stmt->execute();
            $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            $category = $stmt->fetch();
            $imageExtension = $category['extension'];

            $stmt = $conn->prepare("DELETE  FROM categories  WHERE catid= :catid");
            $stmt->bindParam(':catid', $_POST['catid']);
            $stmt->execute();

            $this->delete_image($this->getImageDir(), "category" . $_POST['catid'] . "." . $imageExtension);

//            echo "Delete Category successfully!<br/>";
        }catch (PDOException $e){
            throw new Exception("CAN NOT delete the category which still contains some products!");
        }

    }
}